class Solution
{
public:
    vector<int> intersect(vector<int> &nums1, vector<int> &nums2)
    {
        vector<int> count1(1001, 0), count2(1001, 0);
        for (int num : nums1)
        {
            ++count1[num];
        }
        for (int num : nums2)
        {
            ++count2[num];
        }
        vector<int> result;
        for (int i = 0; i <= 1000; ++i)
        {
            int count = min(count1[i], count2[i]);
            if (count != 0)
            {
                result.insert(result.end(), count, i);
            }
        }
        return result;
    }
};